<!DOCTYPE html>
<html>

<head>
  <meta charset='utf-8' />
  <title>Mapbox Flat Cap Line</title>
  <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
  <script src='https://api.mapbox.com/mapbox-gl-js/v2.3.1/mapbox-gl.js'></script>
  <link href='https://api.mapbox.com/mapbox-gl-js/v2.3.1/mapbox-gl.css' rel='stylesheet' />
  <script src='https://npmcdn.com/@turf/turf/turf.min.js'></script>
  <style>
    body {
      margin: 0;
      padding: 0;
    }

    #map {
      position: absolute;
      top: 0;
      bottom: 0;
      width: 100%;
    }
  </style>
</head>

<body>
  <div id='map'></div>
  <script>
    mapboxgl.accessToken = 'pk.eyJ1IjoibGlud2VpOTIxMjE5IiwiYSI6ImNrb2pwbnM5dTFpZ3UybnB3dHlnc2M3dGsifQ.XbmGjeu_6Fr9qByZQxsvkQ';
    var map = new mapboxgl.Map({
      container: 'map',
      style: 'mapbox://styles/mapbox/streets-v11',
      center: [-122.4194, 37.7749],
      zoom: 12
    });

    map.on('load', function () {
      // 添加平头拐角的线源和图层
      map.addSource('line', {
        'type': 'geojson',
        'data': {
          'type': 'FeatureCollection',
          'features': [{
            'type': 'Feature',
            'properties': {},
            'geometry': {
              'type': 'LineString',
              'coordinates': [
                [-122.4194, 37.7749],
                [-122.4253, 37.7736],
                [-122.4269, 37.7648],
                [-122.4335, 37.7662]
              ]
            }
          }]
        }
      });
      map.addLayer({
        'id': 'line-layer',
        'type': 'line',
        'source': 'line',
        'layout': {
          'line-cap': 'butt', // 设置平头线
          'line-join': 'miter' // 设置拐角类型为miter
        },
        'paint': {
          'line-color': '#f00',
          'line-width': 10 // 设置线宽度
        }
      });

      // 缓冲区域
      var bufferSource = turf.buffer(map.getSource('line')._data.features[0], 10, { units: 'meters', joinStyle: 'miter', endCapStyle: 'butt' });
      map.addSource('buffer', {
        'type': 'geojson',
        'data': bufferSource
      });
      map.addLayer({
        'id': 'buffer-layer',
        'type': 'fill',
        'source': 'buffer',
        'paint': {
          'fill-color': '#00f',
          'fill-opacity': 0.5,
          'fill-outline-color': '#000'
        }
      });
    });

  </script>
</body>

</html>